package com.ruoyi.market.service.sms;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.db.entity.SmsConfigInfo;
import com.ruoyi.market.model.result.SmsInfoResult;
import com.ruoyi.market.service.ISmsInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class DanMiSmsInfoService implements ISmsInfoService {


    @Override
    public SmsInfoResult getSmsInfo(SmsConfigInfo smsConfigInfo) {

        SmsInfoResult smsInfoResult = new SmsInfoResult();
        smsInfoResult.setPlatformName("旦米");
        smsInfoResult.setSuccess(false);
        try {
            HttpRequest httpRequest = HttpUtil.createPost(smsConfigInfo.getQueryUrl());

            String timestamp = String.valueOf(System.currentTimeMillis());
            String sign = SecureUtil.md5(smsConfigInfo.getAccount() + smsConfigInfo.getSecret() + timestamp);

            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("respDataType", "JSON");
            paramMap.put("accountSid", smsConfigInfo.getAccount());
            paramMap.put("timestamp", timestamp);
            paramMap.put("sig", sign);

            httpRequest.form(paramMap);

            String bodyResult = httpRequest.execute().body();
            log.info("【旦米短信服务】【余额查询】发送结束【requesturl】{}【paramMap】{}【bodyResult】{}",
                    smsConfigInfo.getUrl(), JSON.toJSONString(paramMap), bodyResult);

            JSONObject resultJson = JSON.parseObject(bodyResult);
            String respCode = resultJson.getString("respCode");
            String respDesc = resultJson.getString("respDesc");


            smsInfoResult.setCode(respCode);
            smsInfoResult.setMessage(respDesc);
            if (StrUtil.equals("0000", respCode)){
                String balance = resultJson.getString("balance");
                smsInfoResult.setBalance(balance);
                smsInfoResult.setSuccess(true);
            }
            return smsInfoResult;
        }catch (Exception exception){
            exception.printStackTrace();
            smsInfoResult.setCode("9999");
            smsInfoResult.setMessage(exception.getMessage());
        }
        return smsInfoResult;
    }
}
